//
//  WZOauthViewController.swift
//  weiBo---01
//
//  Created by 王—wagn on 16/4/11.
//  Copyright © 2016年 王—wagn. All rights reserved.
//

import UIKit
import SVProgressHUD

class WZOauthViewController :UIViewController {
    
    let webview = UIWebView()
    override func loadView() {
        view = webview
        webview.delegate = self
    }
    
    override func viewDidLoad() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "popView")
        navigationItem.rightBarButtonItem = UIBarButtonItem( title: "自动填充", target: self, action: "autoWrite")
        
        //发送请求授权
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=1302370676&redirect_uri=http://www.baidu.com"
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL:url!)
        
        webview.loadRequest(request)
    }
    
    @objc private func popView() {
        print("跳出授权")
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoWrite() {
        webview.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'wangchao22290@sina.com', document.getElementById('passwd').value = 'WAzh22290+' ")
    
    }

}

extension WZOauthViewController:UIWebViewDelegate  {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        //跳转设置title的值,
        let webTitle = webview.stringByEvaluatingJavaScriptFromString("document.title")
        title = webTitle
        SVProgressHUD.dismiss()
    }
    
    //协议方法返回值为 bool类型 如果返回 true 就可才正常工作,否则就不能够工作
    //在授权成功的回调页中获取 授权code
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //取得地址
        let urlString = request.URL?.absoluteString ?? ""
        let flag = "code="
        if urlString.containsString(flag) {
        
            let range = urlString.rangeOfString(flag)!
            
            let code = urlString.substringFromIndex(range.endIndex)
           
//            print(code)
            loadAccess(code)
        }
        
        return true
    }
    
    override func loadAccess(code:String) {
    
        let url = "https://api.weibo.com/oauth2/access_token"
        
        
        
    
    
    }
}


